import { toast, hideLoading } from "./util.js"
import storage from './storage'
export const upLoad = {
  // 上传图片 返回一个图片的数组
  async uploadPic(size){
    let chooseImageResult = await this.chooseImage(size)
    let imgArr = await chooseImageResult.tempFilePaths.map(async (item) => {
      let uploadFileResult = await this.uploadFile(item)
      return uploadFileResult.data;
    })
    return new Promise((resolve,reject) => {
      Promise.all(imgArr).then((result)=>{
        toast('上传成功')
        resolve(result)
      }).catch(err => {
        hideLoading()
        reject(err)
      })
    }) 
  },
  uploadFile(file){
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        header: {
          'clientId': getApp().globalData.clientId,
          "Authorization": `Bearer ${storage.get('token')}`,
        },
				url: `${getApp().globalData.server}/resource/oss/upload`,
				filePath: file,
				name: 'file',
				success: function (res) {
          let data = res.data;
          resolve(JSON.parse(data))
				},
				fail: function (err) {
					hideLoading()
					reject(err)
				},
      })
    })
  },
  chooseImage(size){
    return new Promise((resolve,reject) => {
      wx.chooseImage({
        count: size, // 默认9
        sizeType: ['original', 'compressed'],//['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album','camera'],//['album','camera'], // 可以指定来源是相册还是相机，默认二者都有
				mediaType: ['image'],//['image', 'video'], // 可以指定是图片视频，默认二者都有
        success: function (res) {
          const tempFiles = res.tempFiles //包含图片大小的数组
          let answer = tempFiles.every(item => {   //限制上传图片大小为1M,
            return item.size <= 2*1024*1024
          })
          if (!answer) {
            toast('上传图片不能大于2M!')
            return
          }
          resolve(res)
        },
        fail:function(err){
          hideLoading()
          reject("选择文件失败",err)
        }
      })
    })
  },
}